import 'dart:math';

import 'package:craze/common/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:ui';

import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:url_launcher/url_launcher.dart';

class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  State<LoginView> createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  // 返回路径
  String? _returnPath;
  // 是否保留导航栈
  bool _preserveNavStack = false;

  @override
  void initState() {
    super.initState();
    // 延迟获取参数，确保GoRouter已完全初始化
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getReturnPath();
    });
    _usernameController.text = 'lalala';
    _passwordController.text = '123456';
  }

  // 获取返回路径
  void _getReturnPath() {
    final state = GoRouterState.of(context);
    // 从choose_view传递过来的返回路径参数
    _returnPath = state.uri.queryParameters['returnPath'];
    // 获取是否保留导航栈的参数
    _preserveNavStack = state.uri.queryParameters['preserveNavStack'] == 'true';
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: 1.sw,
        height: 1.sh,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.startBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Stack(
            children: [
              // 返回按钮
              Positioned(
                top: 10.h,
                left: 20.w,
                child: GestureDetector(
                  onTap: () => GoRouter.of(context).pop(),
                  child: Icon(
                    MyIcons.iconBack,
                    color: MyColors.white,
                    size: 24.sp,
                  ),
                ),
              ),

              // Main content
              Column(
                children: [
                  SizedBox(height: 0.15.sh),

                  // App logo
                  Container(
                    width: 84.w,
                    height: 84.w,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(MyImages.logo),
                        fit: BoxFit.cover,
                      ),
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  // App name
                  Text(
                    'Craze',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 32.sp,
                      fontWeight: FontWeight.bold,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    ),
                  ),

                  SizedBox(height: 40.h),

                  // Username input
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 40.w),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(30.r),
                      child: BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 10.w),
                          decoration: BoxDecoration(
                            color: Colors.blue.withAlpha(50),
                            borderRadius: BorderRadius.circular(30.r),
                            border: Border.all(
                              color: MyColors.white.withAlpha(50),
                              width: 1.w,
                            ),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withAlpha(30),
                                blurRadius: 10,
                                offset: const Offset(0, 5),
                              ),
                            ],
                          ),
                          child: TextField(
                            controller: _usernameController,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                            ),
                            decoration: InputDecoration(
                              hintText: 'Enter One User Name',
                              hintStyle: TextStyle(
                                color: Colors.white.withAlpha(180),
                                fontSize: 16.sp,
                              ),
                              prefixIcon: Icon(
                                MyIcons.iconRen,
                                color: Colors.white,
                                size: 26.sp,
                              ),
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.symmetric(
                                vertical: 16.h,
                                horizontal: 16.w,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  // Password input
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 40.w),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(30.r),
                      child: BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 10.w),
                          decoration: BoxDecoration(
                            color: Colors.blue.withAlpha(50),
                            borderRadius: BorderRadius.circular(30.r),
                            border: Border.all(
                              color: MyColors.white.withAlpha(50),
                              width: 1.w,
                            ),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withAlpha(30),
                                blurRadius: 10,
                                offset: const Offset(0, 5),
                              ),
                            ],
                          ),
                          child: TextField(
                            controller: _passwordController,
                            obscureText: true,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                            ),
                            decoration: InputDecoration(
                              hintText: 'Input Password',
                              hintStyle: TextStyle(
                                color: Colors.white.withAlpha(180),
                                fontSize: 16.sp,
                              ),
                              prefixIcon: Icon(
                                MyIcons.iconSuo,
                                color: Colors.white,
                                size: 26.sp,
                              ),
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.symmetric(
                                vertical: 16.h,
                                horizontal: 16.w,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  // Sign up link
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'Don\'t have an account ',
                        style: TextStyle(color: Colors.white, fontSize: 14.sp),
                      ),
                      GestureDetector(
                        onTap: () => _navigateToRegister(),
                        child: Text(
                          'Sign up',
                          style: TextStyle(
                            color: Colors.blue,
                            fontWeight: FontWeight.bold,
                            fontSize: 14.sp,
                            decoration: TextDecoration.underline,
                            decorationColor: MyColors.blue,
                          ),
                        ),
                      ),
                    ],
                  ),

                  const Spacer(),

                  // Login button
                  GestureDetector(
                    onTap: _handleLogin,
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 40.w),
                      child: Container(
                        height: 58.h,
                        decoration: BoxDecoration(
                          color: MyColors.blue,
                          borderRadius: BorderRadius.circular(30.r),
                          border: Border.all(
                            color: MyColors.white.withAlpha(100),
                            width: 1.w,
                          ),
                        ),
                        child: Center(
                          child: Text(
                            'Log In',
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                              fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  // Apple login button
                  GestureDetector(
                    onTap: () async {
                      // Apple 登录注册并自动登录
                      try {
                        final credential =
                            await SignInWithApple.getAppleIDCredential(
                              scopes: [
                                AppleIDAuthorizationScopes.email,
                                AppleIDAuthorizationScopes.fullName,
                              ],
                            );
                        final username =
                            credential.email ??
                            credential.userIdentifier ??
                            'apple_${DateTime.now().millisecondsSinceEpoch}';
                        final password = '123456';
                        final authStore = getIt<AuthStore>();
                        final success = await authStore.register(
                          username: username,
                          password: password,
                          name: "User",
                          email: credential.email ?? '',
                        );
                        if (success) {
                          await authStore.login(username, password);
                          MyToast.showSuccess(context, 'Login successful');
                          GoRouter.of(context).go(AppRouter.home);
                        } else {
                          MyToast.showError(
                            context,
                            authStore.errorMessage ?? 'Apple login failed',
                          );
                        }
                      } catch (e) {
                        MyToast.showError(context, 'Apple login failed: \n$e');
                      }
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 40.w),
                      child: Container(
                        height: 58.h,
                        decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.circular(30.r),
                          border: Border.all(
                            color: MyColors.white.withAlpha(100),
                            width: 1.w,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.apple, color: Colors.white, size: 28.sp),
                            SizedBox(width: 8.w),
                            Text(
                              'Continue with Apple',
                              style: TextStyle(
                                fontSize: 14.sp,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 97.h),

                  // Terms and privacy policy
                  Padding(
                    padding: EdgeInsets.only(bottom: 40.h),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          'By Continuing you agree with ',
                          style: TextStyle(
                            color: Colors.white.withAlpha(200),
                            fontSize: 12.sp,
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            WangYe.openUrl(
                              'https://www.freeprivacypolicy.com/live/6ee5cfdb-37a7-43f6-8e15-d7d1c6f445dd',
                            );
                          },
                          child: Text(
                            'Terms of Service',
                            style: TextStyle(
                              color: Colors.white.withAlpha(200),
                              fontSize: 12.sp,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),
                        Text(
                          ' & ',
                          style: TextStyle(
                            color: Colors.white.withAlpha(200),
                            fontSize: 12.sp,
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            WangYe.openUrl(
                              'https://www.freeprivacypolicy.com/live/4002c619-71d5-4b0c-b2a7-506460ac6375',
                            );
                          },
                          child: Text(
                            'Privacy Policy',
                            style: TextStyle(
                              color: Colors.white.withAlpha(200),
                              fontSize: 12.sp,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 处理登录逻辑
  void _handleLogin() {
    AuthHelper.authenticate(
      context: context,
      username: _usernameController.text.trim(),
      password: _passwordController.text.trim(),
      onSuccess: _onLoginSuccess,
    );
  }

  // 登录成功后的处理
  void _onLoginSuccess() {
    // 无论从哪里进入登录页，登录成功后都直接跳转到首页
    context.go('/');
  }

  // 导航到注册页面，并传递返回路径
  void _navigateToRegister() {
    if (_returnPath != null && _returnPath!.isNotEmpty) {
      context.pushNamed(
        'register',
        queryParameters: {'returnPath': _returnPath},
      );
    } else {
      context.push('/register');
    }
  }
}
